package ktor

import com.liftric.kvault.KVault
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.bearerAuth
import io.ktor.client.request.delete
import io.ktor.client.request.get
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.http.path
import ktor.models.ApiResponse
import models.Location
import sendRequest

class KtorLocationsDataSource(
    private val httpClient: HttpClient,
    private val kVault: KVault
) {
    private val token: String
        get() = kVault.string("token") ?: ""

    suspend fun getLocations(): Result<List<Location>?> {
        return sendRequest {
            httpClient.get {
                url {
                    path("/inventory/api/locations")
                }
                bearerAuth(token)
            }.body<ApiResponse<List<Location>>>().data
        }
    }

    suspend fun createLocation(name: String): Result<Int?> {
        return sendRequest {
            httpClient.post {
                url {
                    path("/inventory/api/locations")
                }
                setBody(mapOf("name" to name))
                bearerAuth(token)
            }.body<ApiResponse<Int>>().data
        }
    }

    suspend fun deleteLocation(id: Int): Result<Int?> {
        return sendRequest {
            httpClient.delete {
                url {
                    path("/inventory/api/locations/$id")
                }
                bearerAuth(token)
            }.body<ApiResponse<Int>>().data
        }
    }
}